﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Nollie.Storage;
using System.Threading;
using Nollie.Storage.Database;
using Nollie.Utilities;

namespace Nollie.CacheTypes.Memory
{
	public class MemCache : ICache, IMemCache
	{
		private Dictionary<string, Partition> _partitions = new Dictionary<string, Partition>();
		private ReaderWriterLockSlim _locker = new ReaderWriterLockSlim();

		public MemCache()
		{
		}

		public IPartition GetMemPartition(string partitionName, int inMemoryCacheCapacity)
		{
			using (var lockHelper = new ReaderLockHelper(_locker))
			{
				if (_partitions.ContainsKey(partitionName))
					return _partitions[partitionName];
			}

			var partition = new Partition(this, null, partitionName, PartitionTypes.Mem, inMemoryCacheCapacity);

			using (var lockHelper = new WriterLockHelper(_locker))
			{
				_partitions.Add(partitionName, partition);

				return partition;
			}
		}
		public void ClearAllPartitions()
		{
			using (var lockHelper = new ReaderLockHelper(_locker))
			{
				foreach (var partition in _partitions)
					partition.Value.Clear();
			}
		}
		public void RemoveByTag(string tag)
		{
			using (var lockHelper = new ReaderLockHelper(_locker))
			{ 		
				foreach (var partition in _partitions)
					partition.Value.RemoveByTag(tag);
			}
		}
	}
}
